<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

set_time_limit(0);
ini_set('memory_limit', '128M');

class RollSingleStat extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:RollSingleStat';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->statOldData();
        return 0;
    }

    public function statOldData()
    {
        $id = 122477;
        while (true) {
            echo $id;echo PHP_EOL;
            $sales = DB::table('roll_sales')
                ->leftJoin('roll_master', 'roll_master.id', 'roll_sales.roll_id')
                ->where('roll_sales.id', '>', $id)
                ->select('roll_sales.*', 'roll_master.length as master_length', 'roll_master.film_type_id as roll_type_id', 'roll_master.product_type_id')
                ->paginate(1000);
            if (empty($sales) || $sales->isEmpty()) {
                break;
            }

            foreach ($sales as $sale) {
                $id = $sale->id;
                if ($sale->master_length <= 0) {
                    continue;
                }
                $sales_num = round($sale->length / $sale->master_length, 2);
                $data = DB::table('xpel_single_roll_stat')
                    ->where('roll_id', $sale->roll_id)
                    ->where('create_date', date('Y-m-d', strtotime($sale->date_sold)))
                    ->first();
                if (!empty($data)) {
                    $updateData = [
                        'sales_num' => $data->sales_num + $sales_num
                    ];
                    DB::table('xpel_single_roll_stat')
                        ->where('id', $data->id)
                        ->update($updateData);
                    continue;
                }

                $insertData = [
                    'roll_id'   => $sale->roll_id,
                    'sales_num' => $sales_num,
                    'roll_type_id'  => $sale->roll_type_id,
                    'product_type_id' => $sale->product_type_id,
                    'create_date'   => date('Y-m-d', strtotime($sale->date_sold))
                ];
                DB::table('xpel_single_roll_stat')->insert($insertData);
            }
        }
    }
}
